/*
 * 文件名：CouponCtroller.java
 * 版权：Copyright by www.huawei.com
 * 描述：
 * 修改人：hry
 * 修改时间：2016年5月23日
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package com.zcsy.seller.web.coupon;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.model.RequestConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.unique.UniqueNumberUtils;
import com.zcsy.commons.util.DateUtils;
import com.zcsy.manage.model.base.CellInfo;
import com.zcsy.manage.model.base.ShopInfo;
import com.zcsy.manage.model.mall.CouponDetail;
import com.zcsy.manage.model.mall.CouponInfo;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.service.base.ICellInfoService;
import com.zcsy.manage.service.base.IShopInfoService;
import com.zcsy.manage.service.mall.ICouponDetailService;
import com.zcsy.manage.service.mall.ICouponInfoService;
import com.zcsy.seller.web.tools.JExcelReport;

/**
 * 
 * @Title: CouponController.java @Package： com.zcsy.seller.web.coupon
 * @Description: 优惠券信息控制层
 *
 * @author lilan 1063972142@qq.com
 * @Copyright: 2015 武汉恒数利通信息技术有限公司 All rights reserved.
 * @date 2016年6月6日
 * @version 1.0
 * @see JDK1.7.0_75
 * @since
 */
@Controller
@RequestMapping(value = "coupon")
public class CouponController {

    @Autowired
    private ICouponInfoService couponInfoService;
    @Autowired
    private ICouponDetailService couponDetailService;
    @Autowired
    private ICellInfoService cellInfoService;
    @Autowired
    private IShopInfoService shopInfoService;

    private static final int PAGE_SIZE = 4; // 每页大小
    private static final int PAGE_NO = 1; // 默认首页
    /** 正常 */
    private static final int STATE_SUCCESS = 2;
    /** 商户禁用 */
    private static final int STAET_FORBIDEN = 5;
    /** 商户 */
    private static final int TYPE_BUSINESS = 2;
    /** 商户优惠券类型 */
    private static final int COUPON_BUSINESS = 3;
    /** 优惠券初始状态 */
    private static final int COUPON_STATE = -1;
    /** 优惠券初始状态 */
    private static final int COUPON_STATE_SEND = 2;
    /** 优惠券初始状态 */
    private static final int COUPON_STATE_USED = 3;

    /**
     * @Description 返回优惠券申请列表页面<br>
     * @param model
     * @param pNo
     *            当前页
     * @param userAccount
     *            发布账号
     * @param req
     *            用户请求
     * @return
     * @author lilan 1063972142@qq.com
     * @date 2016年4月21日
     * @see
     */
    @RequestMapping(value = "/couponApply", method = RequestMethod.GET)
    public String couponApply(Model model, String id) {

        try {
            if (String.valueOf(Constants.STATE_DISABLED).equals(id)) {
                model.addAttribute("type", Constants.SAVE_TYPE);
            } else {
                CouponInfo couponInfo = couponInfoService.selectByPrimaryKey(id);
                if (couponInfo != null) {
                    model.addAttribute("type", Constants.EDIT_TYPE);
                    model.addAttribute("couponInfo", couponInfo);
                    model.addAttribute("cellid", couponInfo.getCellId());
                    model.addAttribute("shopid", couponInfo.getShopId());
                }
            }
            List<CellInfo> cellInfos = cellInfoService.getAllCellInfo();
            List<ShopInfo> shopInfos = shopInfoService.getAllShopInfo();

            model.addAttribute("cellinfos", cellInfos);
            model.addAttribute("shopinfos", shopInfos);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return "coupon/couponApply";
    }

    /**
     * 
     * @Description 更改发布账号状态<br>
     * 
     * @param model
     * @param id
     *            主键id
     * @param state
     *            1新申请 2正常 3禁用 4已拒绝
     * @return
     * @author lilan 1063972142@qq.com
     * @date 2016年4月21日
     * @see
     */
    @RequestMapping(value = "/couponApplyUpdate", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson adApplyUpdate(Model model, String id, int state) {
        RequestJson result = new RequestJson();
        int temp = 0;
        try {
            CouponInfo couponInfo = couponInfoService.selectByPrimaryKey(id);
            switch (state) {
            // case STATE_NEW:
            // temp = STATE_UNAPPROVED;
            // break;
            // case STATE_UNAPPROVED:
            // temp = STATE_NEW;
            // break;
            case STATE_SUCCESS:
                temp = STAET_FORBIDEN;
                break;
            case STAET_FORBIDEN:
                temp = STATE_SUCCESS;
                break;
            default:
                temp = STATE_SUCCESS;
                break;
            }
            couponInfo.setState(temp);
            couponInfoService.update(couponInfo);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * @Description 返回优惠券信息列表页面<br>
     * @param model
     * @param pNo
     *            当前页
     * @param name
     *            优惠券名称
     * @param cellId
     *            小区ID
     * @param shopId
     *            店铺ID
     * @param req
     *            用户请求
     * @return
     * @author lilan 1063972142@qq.com
     * @throws ParseException
     * @date 2016年4月25日
     * @see
     */
    @RequestMapping(value = "/couponInfoList", method = RequestMethod.GET)
    public String couponInfoList(Model model, Integer pNo, Integer selectState, HttpServletRequest req)
            throws ParseException {

        if (pNo == null) {
            pNo = PAGE_NO;
        }
        // 此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
        PageHelper.startPage(pNo, PAGE_SIZE);

        CouponInfo couponInfo = new CouponInfo();
        couponInfo.setSelectState(selectState);
        ShopInfo shopInfo = (ShopInfo) req.getSession().getAttribute(RequestConstants.SHOP_ID);
        couponInfo.setShopId(shopInfo.getId());

        List<CouponInfo> couponInfos = couponInfoService.selectByTime(couponInfo);
        PageInfo<CouponInfo> info = new PageInfo<CouponInfo>(couponInfos);
        List<CellInfo> cellInfos = cellInfoService.getAllCellInfo();
        List<ShopInfo> shopInfos = shopInfoService.getAllShopInfo();

        model.addAttribute("cellinfos", cellInfos);
        model.addAttribute("shopinfos", shopInfos);
        model.addAttribute("couponInfo", info);
        model.addAttribute("currentPage", pNo);
        model.addAttribute("selectState", selectState);

        return "coupon/couponInfoList";
    }

    /**
     * 
     * @Description 保存和更新优惠券信息页面<br>
     * 
     * @param name
     *            优惠券名称
     * @param id
     *            主键ID
     * @param breakLine
     *            减免线
     * @param breakPrice
     *            减免金额
     * @param beginDate
     *            开始时间
     * @param endDate
     *            结束时间
     * @param count
     *            数量
     * @param userAccount
     *            发布账号
     * @param userAccountType
     *            账号类型
     * @param req
     *            用户请求
     * @return
     * @author lilan 1063972142@qq.com
     * @date 2016年4月25日
     * @see
     */
    @RequestMapping(value = "saveOrUpdateCouponInfo", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson saveOrUpdateCouponInfo(String name, String id, BigDecimal breakLine, BigDecimal breakPrice,
            String beginDate, String endDate, Integer count, String useBeginDate, String useEndDate,
            HttpServletRequest req) {
        
        RequestJson result = new RequestJson();
        
        try {
            if (id != "" && !"0".equals(id)) {//更新优惠券
                CouponInfo couponInfo = couponInfoService.selectByPrimaryKey(id);
                
                couponInfo.setName(name);
                couponInfo.setBreakLine(breakLine);
                couponInfo.setBreakPrice(breakPrice);
                couponInfo.setBeginDate(beginDate);
                couponInfo.setEndDate(endDate);
                couponInfo.setCount(count);
                couponInfo.setUseBeginDate(useBeginDate);
                couponInfo.setUseEndDate(useEndDate);
                couponInfo.setState(STATE_SUCCESS);
                couponInfo.setType(COUPON_BUSINESS);
                couponInfo.setUserAccountType(TYPE_BUSINESS);
                ShopInfo shopInfo = (ShopInfo) req.getSession().getAttribute(RequestConstants.SHOP_ID);
                couponInfo.setShopId(shopInfo.getId());
                User user = (User) req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
                couponInfo.setUserAccount(user.getLoginname());
                couponInfo.setCreateTime(DateUtils.getDate());
                couponInfoService.update(couponInfo);
            } else {//添加优惠券
                CouponInfo couponInfo = new CouponInfo();
                
                couponInfo.setId(UniqueNumberUtils.get18UniqueNumber());
                couponInfo.setName(name);
                couponInfo.setBreakLine(breakLine);
                couponInfo.setBreakPrice(breakPrice);
                couponInfo.setBeginDate(beginDate);
                couponInfo.setEndDate(endDate);
                couponInfo.setCount(count);
                couponInfo.setUseBeginDate(useBeginDate);
                couponInfo.setUseEndDate(useEndDate);
                couponInfo.setState(STATE_SUCCESS);
                couponInfo.setType(COUPON_BUSINESS);
                couponInfo.setUserAccountType(TYPE_BUSINESS);
                
                ShopInfo shopInfo = (ShopInfo) req.getSession().getAttribute(RequestConstants.SHOP_ID);
                couponInfo.setShopId(shopInfo.getId());
                User user = (User) req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
                couponInfo.setUserAccount(user.getLoginname());
                couponInfo.setCreateTime(DateUtils.getDate());
                couponInfoService.insert(couponInfo);
            }
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg("操作失败");
        }

        return result;
    }

    /**
     * @Description 返回优惠券申请列表页面<br>
     * @param model
     * @param pNo
     *            当前页
     * @param userAccount
     *            发布账号
     * @param req
     *            用户请求
     * @return
     * @author lilan 1063972142@qq.com
     * @date 2016年4月21日
     * @see
     */
    @RequestMapping(value = "/couponDetail", method = RequestMethod.GET)
    public String adApply(Model model, Integer pNo, Integer state, String couponId, String couponName,
            HttpServletRequest req) {
        if (pNo == null) {
            pNo = PAGE_NO;
        }
        // 此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
        PageHelper.startPage(pNo, PAGE_SIZE);

        ShopInfo shopInfo = (ShopInfo) req.getSession().getAttribute(RequestConstants.SHOP_ID);
        CouponDetail couponDetail = new CouponDetail();
        if (state == null) {
            state = COUPON_STATE;
        }
        couponDetail.setState(state);
        if (StringUtils.isNotEmpty(couponName)) {
            couponDetail.setCouponName(couponName);
        }
        if (StringUtils.isNotEmpty(couponId)) {
            couponDetail.setCouponId(couponId);
        }

        couponDetail.setShopId(shopInfo.getId());

        List<CouponDetail> couponDetails = couponDetailService.selectDetailByKeyword(couponDetail);
        PageInfo<CouponDetail> info = new PageInfo<CouponDetail>(couponDetails);

        CouponInfo couponInfo = new CouponInfo();
        couponInfo.setShopId(shopInfo.getId());

        List<CouponInfo> couponInfos = couponInfoService.selectCouponinfo(couponInfo);
        model.addAttribute("couponInfos", couponInfos);
        model.addAttribute("couponDetail", info);
        model.addAttribute("couponstate", state);
        model.addAttribute("couponName", couponName);
        model.addAttribute("couponId", couponId);
        model.addAttribute("currentPage", pNo);

        return "coupon/couponDetail";
    }

    /**
     * 
     * @Description 导出对应的优惠券发放和使用清单<br>
     * 
     * @param id
     *            主键ID
     * @param response
     *            用户响应
     * @author lilan 1063972142@qq.com
     * @date 2016年5月24日
     * @see
     */
    @RequestMapping("/exportCouponDetailExcel")
    @ResponseBody
    public void exportCouponDetailExcel(Model model, String id, Integer couponstate, HttpServletResponse response) {
        List<CouponDetail> list;
        CouponDetail record = new CouponDetail();

        if (StringUtils.isNotEmpty(id)) {
            record.setCouponId(id);
        }
        if (couponstate == null) {
            couponstate = COUPON_STATE;
        }

        record.setState(couponstate);
        try {
            // 得到导出的数据列表
            list = couponDetailService.selectByKeyword(record);

            // 将优惠券信息对象转化为到处所需要的数据格式
            if (list.size() > 0) {
                ArrayList<ArrayList<String>> dataList = new ArrayList<ArrayList<String>>();
                int index = 1;
                for (CouponDetail detail : list) {
                    ArrayList<String> temp = new ArrayList<String>();
                    // 序号
                    temp.add(String.valueOf(index++));
                    // temp.add(detail.getId());
                    temp.add(detail.getCouponName());
                    temp.add(detail.getUserAccount());
                    temp.add(detail.getCouponCode());
                    temp.add(detail.getCode());
                    Integer states = detail.getState();
                    if (states == COUPON_STATE_SEND) {
                        temp.add("已下发");
                    }
                    if (states == COUPON_STATE_USED) {
                        temp.add("已使用");
                    }
                    temp.add(detail.getPhone());
                    temp.add(detail.getImei());
                    temp.add(DateUtils.formatDate(detail.getUseTime()));
                    temp.add(DateUtils.formatDate(detail.getExpireTime()));
                    temp.add(DateUtils.formatDate(detail.getCreateTime()));
                    dataList.add(temp);
                }
                // 导出标题列
                // String[] rows = new String[]
                // {"序号","优惠券名称","发布账号","优惠券信息编码","优惠券详情编码",
                // "优惠券状态","电话","imei","使用时间","过期时间","创建时间"};
                String[] rows = "序号,优惠券名称,发布账号,优惠券信息编码,优惠券详情编码,优惠券状态,电话,imei,使用时间,过期时间,创建时间".split(",");
                // 导出excel文件每列宽度
                int[] style = new int[] { 5, 20, 20, 20, 20, 20, 20, 20, 20, 20 };
                // Excel文件sheet名称
                String sheetName = "优惠券" + list.get(0).getCouponName() + "发放和使用清单" + DateUtils.getCurrentDate();
                String fileName = "优惠券" + list.get(0).getCouponName() + "发放和使用清单";
                doExecl(response, fileName, sheetName, dataList, rows, style);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
    }

    /**
     * 
     * @Description 导出优惠券详情信息
     * 
     * @param model
     * @param couponId
     *            优惠券id
     * @param couponName
     *            优惠券名称
     * @param state
     *            优惠券状态 2：已发放，3：已使用
     * @param response
     *            用户响应
     * @param req
     *            用户请求
     * @author lilan 1063972142@qq.com
     * @date 2016年6月6日
     * @see
     */
    @RequestMapping("/exportExcel")
    @ResponseBody
    public void exportExcel(Model model, String couponId, String couponName, Integer state,
            HttpServletResponse response, HttpServletRequest req) {
        List<CouponDetail> list;
        CouponDetail record = new CouponDetail();
        if (StringUtils.isNotEmpty(couponId)) {
            record.setCouponId(couponId);
        }
        if (StringUtils.isNotEmpty(couponName)) {
            record.setCouponName(couponName);
        }
        if (state == null) {
            state = COUPON_STATE;
        }
        ShopInfo shopInfo = (ShopInfo) req.getSession().getAttribute(RequestConstants.SHOP_ID);
        record.setShopId(shopInfo.getId());
        record.setState(state);
        try {
            // 得到导出的数据列表
            list = couponDetailService.selectDetailByKeyword(record);

            // 将优惠券信息对象转化为到处所需要的数据格式
            if (list.size() > 0) {
                ArrayList<ArrayList<String>> dataList = new ArrayList<ArrayList<String>>();
                int index = 1;
                for (CouponDetail detail : list) {
                    ArrayList<String> temp = new ArrayList<String>();
                    // 序号
                    temp.add(String.valueOf(index++));
                    // temp.add(detail.getId());
                    temp.add(detail.getCouponName());
                    temp.add(detail.getUserAccount());
                    temp.add(detail.getCouponCode());
                    temp.add(detail.getCode());
                    Integer states = detail.getState();
                    if (states == COUPON_STATE_SEND) {
                        temp.add("已下发");
                    }
                    if (states == COUPON_STATE_USED) {
                        temp.add("已使用");
                    }
                    temp.add(detail.getPhone());
                    temp.add(detail.getImei());
                    temp.add(DateUtils.formatDate(detail.getUseTime()));
                    temp.add(DateUtils.formatDate(detail.getExpireTime()));
                    temp.add(DateUtils.formatDate(detail.getCreateTime()));
                    dataList.add(temp);
                }
                // 导出标题列
                String[] rows = new String[] { "序号", "优惠券名称", "发布账号", "优惠券信息编码", "优惠券详情编码", "优惠券状态", "电话", "imei",
                        "使用时间", "过期时间", "创建时间" };
                // 导出excel文件每列宽度
                int[] style = new int[] { 5, 20, 20, 20, 20, 20, 20, 20, 20, 20 };
                // Excel文件sheet名称
                String sheetName = "优惠券" + "发放和使用清单" + DateUtils.getCurrentDate();
                String fileName = "优惠券" + "发放和使用清单";
                doExecl(response, fileName, sheetName, dataList, rows, style);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
    }

    /**
     * 
     * @Description 通过传入的对象信息集合产生的excel表格<br>
     * 
     * @param response
     *            用户响应
     * @param sheetName
     *            excel表名称
     * @param dataList
     *            传入的数据列表
     * @param rows
     *            excel表的列控制，名称
     * @param style
     *            规定列宽等样式
     * @throws Exception
     * @author lilan 1063972142@qq.com
     * @date 2016年5月24日
     * @see
     */
    private void doExecl(HttpServletResponse response, String tempName, String sheetName,
            ArrayList<ArrayList<String>> dataList, String[] rows, int[] style) throws Exception {
        // 输出的excel名称为中文，否则发生错误
        String tempFileName = tempName + ".xls";
        String fileName = new String(tempFileName.getBytes("GB2312"), "ISO_8859_1");

        ServletOutputStream fout = response.getOutputStream();
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "filename=" + fileName + "");
        JExcelReport jexcelOutStream = new JExcelReport();
        try {
            jexcelOutStream.excelreport(sheetName, dataList, rows, fout, style);
            fout.flush();
            fout.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
